<template>
  <div>
    <slot>
      <p class="text-sm">
        {{ showTime }}
      </p>
    </slot>
  </div>
</template>
<script>
const EMITS_FINISH = 'finish'
const EMITS_CHANGE = 'change'
const DURATION_COUNT = 1000
</script>
<script setup>
import { watch, ref, onUnmounted, computed } from 'vue'
import dayjs from './utils'
const props = defineProps({
  timeDate: {
    type: Number,
    required: true
  },
  //day js标准时间格式
  format: {
    type: String,
    default: 'HH:mm:ss'
  }
})
const durition = ref(0)
const emits = defineEmits([EMITS_FINISH, EMITS_CHANGE])
let intrval = null
const start = () => {
  close()
  intrval = setInterval(() => {
    durationFn()
  }, DURATION_COUNT)
}
const durationFn = () => {
  durition.value -= DURATION_COUNT
  emits(EMITS_CHANGE, durition.value)
  if (durition.value <= 0) {
    durition.value = 0
    close()
    emits(EMITS_FINISH)
  }
}

const close = () => {
  if (intrval) {
    clearInterval(intrval)
  }
}
watch(
  () => props.timeDate,
  (val) => {
    durition.value = val
    start()
  },
  {
    immediate: true
  }
)
//组件销毁时清空组件
onUnmounted(() => {
  close()
})
const showTime = computed(() => {
  return dayjs.duration(durition.value).format(props.format)
})
</script>
<style lang="scss"></style>
